package com.info.zhiduoduo.pay.sdk.alipaysdk;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransCommonQueryModel;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayDataBillBalanceQueryRequest;
import com.alipay.api.request.AlipayFundTransCommonQueryRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayDataBillBalanceQueryResponse;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.utils.ContextUtil;
import com.info.zhiduoduo.pay.configs.alipay.base.BaseAlipayConfig;
import com.info.zhiduoduo.pay.formbean.zhaoshangbankpay.AlipayAccountQueryFormBean;
import com.info.zhiduoduo.pay.formbean.zhaoshangbankpay.AlipayTransferFormBean;
import com.info.zhiduoduo.pay.formbean.zhaoshangbankpay.AlipayTransferQueryFormBean;
import com.info.zhiduoduo.pay.sdk.alipaysdk.constant.AlipayTransPrincipalEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 安全发（人资ISV版）文档: https://opendocs.alipay.com/open/01kwnq
 */
@Service
@Slf4j
public class AliPayBaseApiService {

    /**
     * 获取接口客户端
     *
     * @param alipayConfig 支付宝配置
     * @return
     */
    private AlipayClient getAlipayClient(BaseAlipayConfig alipayConfig) {
        return new DefaultAlipayClient(alipayConfig.getAlipayGateway(), alipayConfig.getAppId(), alipayConfig.getAppPrivateKey(), "json",
                alipayConfig.getAlipayCharset(), alipayConfig.getAlipayPublicKey(), alipayConfig.getAlipaySignType());
    }

    /**
     * 获取接口客户端
     *
     * @param isv 智多多平台的支付宝业务类型
     * @return
     */
    private AlipayClient getAlipayClient(AlipayTransPrincipalEnum isv) {
        return getAlipayClient(ContextUtil.getBean(isv.config));
    }

    /**
     * 获取使用密钥证书的接口客户端
     *
     * @param paymentMerchant
     * @return
     * @throws AlipayApiException
     */
    private DefaultAlipayClient getCertAlipayClient(int paymentMerchant) throws AlipayApiException {
        AlipayTransPrincipalEnum isv = AlipayTransPrincipalEnum.findById(paymentMerchant);
        BaseAlipayConfig alipayConfig = ContextUtil.getBean(isv.config);
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(alipayConfig.getAlipayGateway());
        certAlipayRequest.setAppId(alipayConfig.getAppId());
        certAlipayRequest.setPrivateKey(alipayConfig.getAppPrivateKey());
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset(alipayConfig.getAlipayCharset());
        certAlipayRequest.setSignType(alipayConfig.getAlipaySignType());
        certAlipayRequest.setCertPath(alipayConfig.getAppCertPublicKeyPath());
        certAlipayRequest.setAlipayPublicCertPath(alipayConfig.getAlipayCertPublicKeyPath());
        certAlipayRequest.setRootCertPath(alipayConfig.getAlipayRootCertPath());
        return new DefaultAlipayClient(certAlipayRequest);
    }

    /**
     * 调用免密单笔转账接口
     *
     * @param formBean
     * @throws AlipayApiException
     */
    public AlipayFundTransUniTransferResponse transfer(AlipayTransferFormBean formBean) {
        try {
            DefaultAlipayClient alipayClient = getCertAlipayClient(formBean.getPaymentMerchant());
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            model.setOutBizNo(formBean.getTradeNo());
            model.setRemark("");
            model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
            model.setBizScene("DIRECT_TRANSFER");
            Participant payeeInfo = new Participant();
            payeeInfo.setIdentity(formBean.getIdentity());
            payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
            payeeInfo.setName(formBean.getName());
            model.setPayeeInfo(payeeInfo);
//            model.setTransAmount(formBean.getAmount().toString());
            //测试先用0.1
            if (!ContextUtil.isProd()) {
                model.setTransAmount("0.1");
            } else {
                model.setTransAmount(formBean.getAmount().toString());
            }
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
//            model.setOrderTitle(formBean.getDescribe());
            request.setBizModel(model);
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            log.info("调用alipay SDK, 单笔免密转账结果: {}", JSON.toJSONString(response));
            return response;
        } catch (AlipayApiException e) {
            log.error("调用免密单笔转账接口", e);
            throw SmartException.of(StatusMsg.StatusMsg_199);
        }
    }

    /**
     * 调用免密单笔转账接口
     *
     * @param formBean
     * @throws AlipayApiException
     */
    public AlipayFundTransCommonQueryResponse transferQuery(AlipayTransferQueryFormBean formBean) {
        try {
            DefaultAlipayClient alipayClient = getCertAlipayClient(formBean.getPaymentMerchant());
            AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
            AlipayFundTransCommonQueryModel model = new AlipayFundTransCommonQueryModel();
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            model.setBizScene("DIRECT_TRANSFER");
            model.setOutBizNo(formBean.getTradeNo());
            request.setBizModel(model);
            AlipayFundTransCommonQueryResponse response = alipayClient.certificateExecute(request);
            log.info("调用alipay SDK, 单笔免密转账查询结果: {}", JSON.toJSONString(response));
            return response;
        } catch (AlipayApiException e) {
            log.error("调用免密单笔免密转账查询接口", e);
            throw SmartException.of(StatusMsg.StatusMsg_199);
        }
    }

    /**
     * 支付宝资金账户资产查询接口
     *
     * @param formBean
     * @throws AlipayApiException
     */
    public AlipayDataBillBalanceQueryResponse accountQuery(AlipayAccountQueryFormBean formBean) {
        try {
            DefaultAlipayClient alipayClient = getCertAlipayClient(formBean.getPaymentMerchant());
            AlipayDataBillBalanceQueryRequest request = new AlipayDataBillBalanceQueryRequest();
            AlipayDataBillBalanceQueryResponse response = alipayClient.certificateExecute(request);
            log.info("调用alipay SDK, 余额查询结果: {}", JSON.toJSONString(response));
            return response;
        } catch (AlipayApiException e) {
            log.error("调用免密单笔免密转账查询接口", e);
            throw SmartException.of(StatusMsg.StatusMsg_199);
        }
    }
}
